package com.springboot.demo.io;

import java.nio.ByteBuffer;

/**
 * ByteBuffer 测试
 *
 * @author supu
 * @since 2020-11-13 15:55
 **/
public class ByteBufferTest {
    public static void main(String[] args) {
        ByteBufferTest byteBufferTest = new ByteBufferTest();
        byteBufferTest.bufferTest();
    }

    public void bufferTest(){
        // 堆内 buffer
        ByteBuffer byteBuffer1 = ByteBuffer.allocate(1024);
        // 堆外 buffer
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);

        System.out.println("position : " + byteBuffer.position());
        System.out.println("limit : " + byteBuffer.limit());
        System.out.println("capacity : " + byteBuffer.capacity());
        System.out.println("mark : " + byteBuffer.mark());

        byteBuffer.put("123abc".getBytes());

        System.out.println("-------------put:123abc......");
        System.out.println("put: " + byteBuffer);

        //读写交替
        byteBuffer.flip();

        System.out.println("-------------flip......");
        System.out.println("flip: " + byteBuffer);

        // 读取一个字节数据
//        byteBuffer.get();
        byte[] bytes = new byte[1];
        byteBuffer.get(bytes);
        System.out.println("flip after read ：" + new String(bytes));

        System.out.println("-------------get......");
        System.out.println("get: " + byteBuffer);

        byteBuffer.compact();

        System.out.println("-------------compact......");
        System.out.println("compact: " + byteBuffer);

        byteBuffer.clear();

        System.out.println("-------------clear......");
        System.out.println("clear: " + byteBuffer);

        byte[] bytes1 = new byte[1];
        byteBuffer.get(bytes1);
        System.out.println("clear after read ：" + new String(bytes1));
    }
}
